﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.DAL;
using Gift.Model;
using Gift.Model.ENUM;
using Gift.Security;

namespace WebSite.admin.product
{
    public partial class card_add : BaseAdmin
    {

        readonly Card theCard = new Card();
        readonly dalCompany theCompany = new dalCompany();
        readonly DALCardType theCardType = new DALCardType();



        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                this.txtSartTime.Value = DateTime.Now.ToString("yyyy-MM-dd");
                base.ValidateLoginRule(ERule.AddGiftCard);
                this.BindCompanyList();
                this.BindCardTypeList();
            }
        }

        void BindCardTypeList()
        {
            DataSet ds;
            ds = theCardType.GetList(" 1=1" );
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = ds.Tables[0].DefaultView;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ListItem("请选择...", ""));
        }

        void BindCompanyList()
        {
            DataSet dsCompany = theCompany.GetList("CompanyTypeId=1");
            this.ddlCompany.DataTextField = "Name";
            this.ddlCompany.DataValueField = "Id";
            this.ddlCompany.DataSource = dsCompany.Tables[0].DefaultView;
            this.ddlCompany.DataBind();
            this.ddlCompany.Items.Insert(0,new ListItem("请选择...",""));
        }



        public string turn(string str)
        {
            str = str.Replace("\n", "+");
            return str;
        }


        string GenerateBeforCode()
        {
            string sBeforCode = "";
            Random random = new Random();
            sBeforCode = random.Next(1000, 9999).ToString();
            if (theCard.IsExistsBefor(sBeforCode))
            {
               return GenerateBeforCode();
            }
            else
            {
                return sBeforCode;
            }
        }


        protected void ibtnGenerate_Click(object sender, ImageClickEventArgs e)
        {
            if(theCard.IsExistsBefor(this.befornumber.Value))
            {
                base.Response.Write("<script language='javascript'>alert('礼品卡前面数字已存在，请重新输入！');</script>");
                return;
            }

            Random random = new Random();
            string sBeforCode =  this.befornumber.Value;// GenerateBeforCode();
            List<dbCard> lstInfo;
            lstInfo = new List<dbCard>();
            dbCard theCardInfo;
            DateTime dtStartTime;
            DateTime dtEndTime;
            DateTime dtLastTime;

            if (string.IsNullOrEmpty(this.txtSartTime.Value))
            {
                dtStartTime = DateTime.Now;
            }
            else
            {
                if (DateTime.TryParse(this.txtSartTime.Value, out dtStartTime))
                {
                    dtStartTime = DateTime.Parse(this.txtSartTime.Value);
                }
                else
                {
                    dtStartTime = DateTime.Now;
                }
            }

            if (string.IsNullOrEmpty(this.endtime.Value))
            {
                dtEndTime = DateTime.Now.AddMonths(6);
            }
            else
            {
                if (DateTime.TryParse(this.endtime.Value, out dtEndTime))
                {
                    dtEndTime = DateTime.Parse(this.endtime.Value);
                }
                else
                {
                    dtEndTime = DateTime.Now.AddMonths(6);
                }
            }

            if (string.IsNullOrEmpty(this.lasttime.Value))
            {
                dtLastTime = DateTime.Now.AddMonths(8);
            }
            else
            {
                if (DateTime.TryParse(this.lasttime.Value, out dtLastTime))
                {
                    dtLastTime = DateTime.Parse(this.lasttime.Value);
                }
                else
                {
                    dtLastTime = DateTime.Now.AddMonths(8);
                }
            }
            decimal money;
            int iAfter;
            string tempAfter = "1";
            for (int j = 0; j < int.Parse(this.afternumber.Value)-1; j++)
            {
                tempAfter = tempAfter + "0"; 
            }
            iAfter = int.Parse(tempAfter);
            money = decimal.Parse(this.cardprice.Value);
            int iMax = iAfter + int.Parse(this.txtCardCount.Value);
            for (int i = iAfter; i < iMax; i++)
            {
                theCardInfo = new dbCard();
                theCardInfo.cardcode = sBeforCode + i.ToString();
                theCardInfo.cardpas = random.Next(10000000, 99999999).ToString();
                theCardInfo.cardprice = money;
                theCardInfo.StartTime = dtStartTime;
                theCardInfo.endtime = dtEndTime;
                theCardInfo.lasttime = dtLastTime;
                theCardInfo.cardtypeId = int.Parse(this.ddlCardType.SelectedItem.Value);
                theCardInfo.companyId = this.ddlCompany.SelectedItem.Value == "" ? 0 :int.Parse(this.ddlCompany.SelectedItem.Value);
                theCardInfo.CardTypeName = this.ddlCardType.SelectedItem.Text;
                lstInfo.Add(theCardInfo);
            }
            ViewState["cardlist"] = lstInfo;
            this.GridView1.DataSource = lstInfo;
            this.GridView1.DataBind();
            this.btnAdd.Visible = true;
            this.btnExport.Visible = true;
        }

        protected void ibtnAdd_Click(object sender, ImageClickEventArgs e)
        {
            List<dbCard> lstCard;
            StringBuilder sbSql = new StringBuilder();
            if (ViewState["cardlist"] != null)
            {
                lstCard = (List<dbCard>)ViewState["cardlist"];
                foreach (dbCard theCard in lstCard)
                {
                 
                    sbSql.Append("INSERT INTO DB_Card(cardcode,cardpas,cardprice,starttime,endtime,lasttime,states,cardtypeId,companyId)");
                    sbSql.Append(" VALUES('" + theCard.cardcode + "','" + DESEncrypt.Encrypt(theCard.cardpas) + "'," + theCard.cardprice.ToString());
                    sbSql.Append(" ,'" + theCard.StartTime.ToString() + "'");
                    sbSql.Append(" ,'" + theCard.endtime.ToString() + "','" + theCard.lasttime.ToString() + "',4," + theCard.cardtypeId.ToString() + "," + theCard.companyId.ToString() + ");");

                }
                SQLAccess.DoSql(sbSql.ToString());
            }

            base.Response.Write("<script language='javascript'>alert('礼品卡添加成功');window.location.href='OpenCard.aspx';</script>");
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            if (ViewState["cardlist"] == null) return;
            List<dbCard> lstCard = (List<dbCard>)ViewState["cardlist"];
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("卡号", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("密码", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("金额", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("礼品卡类别", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("专区开始日期", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("专区截止日期", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("礼品商城截止日期", Type.GetType("System.String")));

            for (int i = 0; i < lstCard.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = lstCard[i].cardcode;
                dr[1] = lstCard[i].cardpas;
                dr[2] = int.Parse(lstCard[i].cardprice.ToString()).ToString();
                dr[3] = lstCard[i].CardTypeName;
                dr[4] =  lstCard[i].StartTime.ToShortDateString();
                dr[5] =  lstCard[i].endtime.ToShortDateString();
                dr[6] =  lstCard[i].lasttime.ToShortDateString();
                dt.Rows.Add(dr);
            }


            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(dt, fileName);
        }


        private  string BuildExportHTML(DataTable dt)
        {
        
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 20000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy年MM月dd日") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }

    }

   
}